package com.liuxing.javaSpringBoot.realm;

import com.liuxing.javaSpringBoot.modules.account.entity.Resource;
import com.liuxing.javaSpringBoot.modules.account.entity.Role;
import com.liuxing.javaSpringBoot.modules.account.entity.User;
import com.liuxing.javaSpringBoot.modules.account.service.ResourceService;
import com.liuxing.javaSpringBoot.modules.account.service.RoleService;
import com.liuxing.javaSpringBoot.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * @File AccountRealm.java
 * @Auth liuxing
 * @Date 2021/8/26 11:20
 * @Email liuxing997@foxmail.com
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;


    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        roles.stream().forEach(item -> {
            simpleAuthorizationInfo.addRole(item.getRoleName());
            List<Resource> resources = resourceService.getResourcesByRoleId(item.getId());
            resources.stream().forEach(it -> {
                simpleAuthorizationInfo.addStringPermission(it.getPermission());
            });
        });
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String)authenticationToken.getPrincipal();
        User user = userService.getUserByUsername(userName);
        if (user != null){
            ByteSource saltBytes = ByteSource.Util.bytes(user.getUserName());
            return new SimpleAuthenticationInfo(user,user.getPassword(),saltBytes,getName());
        }else {
            throw new UnknownAccountException();
        }
    }
}
